const userModel = require('../model/userModel')
//引入md5，用于做数据加密
const md5 = require('md5')


//新建用户（注册）
const createUser = async (userInfo) => {
    let { nickName, gender, phoneNumber, password, imageUrl } = userInfo

    let doc = await userModel.find({phoneNumber})

    if(doc.length == 0){
        try {
            let result = await userModel.create({
                nickName,
                gender,
                phoneNumber,
                password:md5(password),
                imageUrl
            })
    
            return '注册成功'
        } catch (error) {
            console.log(error)
            return Promise.reject('注册失败')
        }
    }else{
        return Promise.reject('该手机号已被注册过')
    }
}

//登录
const login = async (loginInfo) => {
    let { phoneNumber, password } = loginInfo

    try {
        let result = await userModel.findOne({ phoneNumber })

        if (result.length == 0) {
            return '手机号或密码错误'
        }else if(result.password != md5(password)){
            return '手机号或密码错误'
        } else {
            return result
        }

    } catch (error) {
        console.log(error);
        return Promise.reject('登录失败')
    }
}

//获取用户信息
const getUserInfo = async (uid) =>{
    try {
        return await userModel.findById(uid)
    } catch (error) {
        console.log(error);
        return Promise.reject('获取失败')
    }
}

//修改用户信息 此时password无需加密
const updateUserInfo = async (userInfo)=>{
    try {
        let {_id,nickName,gender,phoneNumber,password} = userInfo

        await userModel.findByIdAndUpdate(_id,{$set:{nickName,gender,phoneNumber,password}})
        return 'ok'
    } catch (error) {
        return Promise.reject(error)
    }
}

//修改用户头像
const updateUserAvatar = async (_id,imageUrl)=>{
    try {
        await userModel.findByIdAndUpdate(_id,{$set:{imageUrl}})
        return 'ok'
    } catch (error) {
        console.log('avatar:'+error);
        return Promise.reject(error)
    }
}

module.exports = {
    createUser,
    login,
    getUserInfo,
    updateUserInfo,
    updateUserAvatar
}